package com.yu.dv.autoconfigure;

import com.yu.dv.autoconfigure.properties.DashScopeProperties;
import com.yu.dv.autoconfigure.properties.NaturalLanguageSqlProperties;
import com.yu.dv.service.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@ConditionalOnClass(DataSource.class)
@EnableConfigurationProperties({NaturalLanguageSqlProperties.class, DashScopeProperties.class})
public class NaturalLanguageSqlAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DashScopeClient dashScopeClient(DashScopeProperties properties) {
        return new DashScopeClient(properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public DatabaseMetadataService databaseMetadataService(DataSource dataSource) {
        return new DatabaseMetadataService(dataSource);
    }

    @Bean
    @ConditionalOnMissingBean
    public InputValidator inputValidator(NaturalLanguageSqlProperties properties) {
        return new InputValidator(properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public TextProcessor textProcessor(DatabaseMetadataService databaseMetadataService,
                                       NaturalLanguageSqlProperties properties) {
        return new TextProcessor(databaseMetadataService, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlExecutor sqlExecutor(DataSource dataSource,
                                   NaturalLanguageSqlProperties properties) {
        return new SqlExecutor(dataSource, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public NaturalLanguageToSqlService naturalLanguageToSqlService(InputValidator inputValidator,
                                                                   TextProcessor textProcessor,
                                                                   DashScopeClient dashScopeClient,
                                                                   SqlExecutor sqlExecutor,
                                                                   NaturalLanguageSqlProperties properties) {
        return new NaturalLanguageToSqlService(inputValidator, textProcessor, dashScopeClient, sqlExecutor, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    public NaturalLanguageSqlExceptionHandler naturalLanguageSqlExceptionHandler() {
        return new NaturalLanguageSqlExceptionHandler();
    }

}